import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'package:page_view_dot_indicator/page_view_dot_indicator.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import 'package:wk_robot2/app/widget/CommonWidgets.dart';
import '../../../../generated/AlphaResponse.pb.dart';
import '../../../../generated/GetRobotConfiguration.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../models/ActionItem.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../robot_comm/cmd_const.dart';
import '../../../robot_comm/mqtt_comm_manager.dart';
import '../../../storage/StorageManager.dart';
import '../../../style/app_colors.dart';

@deprecated
class ActionSquaresView2 extends StatefulWidget {
  ActionSquaresView2({super.key});

  @override
  State<StatefulWidget> createState() {
    return ActionSquareViewState();
  }
}

class ActionSquareViewState extends State {

  PageController? _controller;
  int currentIndex = 0;

  bool robotWhetherOnline = false;
  Map<String,List<ActionItem>> actionMp = Map<String, List<ActionItem>>();

  //实际页面.
  List<Widget> items = List.generate(3, (index) => Center(
    child: Text('加载中...'),
  ));

  //虚拟总数.
  int virtualCount = 0;


  bool danceChecked = true;
  bool actionChecked = false;
  bool unexpectedChecked = false;

  @override
  void initState() {
    super.initState();

    //虚拟器总数.
    virtualCount = items.length * 100;
    _controller = PageController(initialPage: items.length * 20);

    /*if (StorageManager.getStorage().hasData(AppConst.CURRENT_DEVICE_ON_LINE)) {
      robotWhetherOnline = StorageManager.getStorage().read(AppConst.CURRENT_DEVICE_ON_LINE);
    }*/

    getActionSquares();

  }


  @override
  void dispose() {
    _controller!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text('动作广场'),
          centerTitle: true,
          leading: IconButton(
            icon: Image.asset('assets/images/ic_back2.png',width: 48.w,height: 48.h),
            onPressed: () {
              Get.back();
            },
            tooltip: MaterialLocalizations.of(context).backButtonTooltip, // 可选：设置工具提示
          ),
          bottom: robotWhetherOnline ? PreferredSize(preferredSize: Size.fromHeight(0.h),child: SizedBox()): PreferredSize(
            preferredSize: Size.fromHeight(72.h),
            child: Container(
              padding: EdgeInsets.only(top: 18.h, bottom: 13.h,left: 40.w),
              color: AppColors.warning_tip_bgColor,
              width: MediaQuery.of(context).size.width,
              child: Text('机器人已经离线,无法执行动作.',style: TextStyle(fontSize: 26.sp,color: Colors.red),),
            ),
          )
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
                flex: 1,
                child: Image.asset('assets/images/ic_dance_default.webp',width: 540.w,height: 460.h)),
            Text('点击下方按钮,就能让悟空动起来！',style: TextStyle(fontSize: 30.sp,color: AppColors.Sub_Title_Color)),
            SizedBox(height: 94.h),
            Expanded(flex:2,
              child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(top: 60.h),
                  child: Column(
                      children: [
                        Container(child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Stack(
                            children: [
                              danceChecked ? Container(
                                margin: EdgeInsets.only(top: 32.h),
                                child:
                                CommonWidgets.getALine(width: 75,height: 12),) : SizedBox(),
                              Text('舞蹈',style: TextStyle(fontSize: 34.sp,color: AppColors.Sub_Title_Color),)
                            ],
                          ),
                          SizedBox(width: 62.w,),
                          Stack(
                            children: [
                              actionChecked ? Container(
                                margin: EdgeInsets.only(top: 32.h),
                                child:
                                CommonWidgets.getALine(width: 75,height: 12),) : SizedBox(),
                              Text('动作',style: TextStyle(fontSize: 34.sp,color: AppColors.Sub_Title_Color))
                            ],
                          ),
                          SizedBox(width: 62.w,),
                          Stack(
                            children: [
                              unexpectedChecked ? Container(
                                margin: EdgeInsets.only(top: 32.h),
                                child:
                                CommonWidgets.getALine(width: 75,height: 12),): SizedBox(),
                              Text('搞怪',style: TextStyle(fontSize: 34.sp,color: AppColors.Sub_Title_Color))
                            ],
                          ),
                        ],
                        )),
                        SizedBox(height: 56.h),
                        Expanded(
                            flex: 1,
                            child: Container(
                              child: PageView.builder(
                                controller: _controller,
                                itemCount: virtualCount, // 使用足够大的itemCount来实现无限滚动
                                itemBuilder: (context, index) {
                                  index = index - 4;
                                  final int realIndex = index % items.length; // 计算真实的索引值

                                  return items[realIndex]; // 返回对应的widget
                                },
                                scrollBehavior: ScrollBehavior(),
                              ),
                            )
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 24),
                          child: PageViewDotIndicator(
                            currentItem: currentIndex,
                            count: items.length,
                            unselectedColor: Colors.black26,
                            selectedColor: Colors.blue,
                            duration: const Duration(milliseconds: 200),
                            boxShape: BoxShape.circle,
                            size: Size(9.w, 9.h),

                          ),
                        ),
                        SizedBox(height: 59.h,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset('assets/images/_ic_warm_black.webp',width: 30.w,height: 30.h,),
                            SizedBox(width: 12.w,),
                            Text('注意让悟空保持在安全平整的地方运动,以免磕碰或跌落！',style: TextStyle(fontSize: 24.sp,color: AppColors.Sub_Title_Color)),
                          ],
                        ),
                        SizedBox(height: 47.h,)
                      ],
                    )
              ),)
          ],
        ),
      ),
    );
  }


  void getActionSquares() {
    //分为在线或不在线.
    if (!robotWhetherOnline) {
      loadingData('Alpha_Mini-UBT','');
    } else {
      GetRobotConfigurationRequest request = GetRobotConfigurationRequest();
      MqttCommManager().sendCmd(CmdConst.IM_GET_ROBOT_CONFIG_REQUEST, request, (AlphaResponse msg){
        GetRobotConfigurationResponse response = GetRobotConfigurationResponse.fromBuffer(msg.bodyData);
        loadingData('Alpha_Mini-UBT',response.hardwareversion);

      });
    }

  }


  void loadingData(String channel,String version) {
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.ACTIONSQUARE_ALL, {
      'channel': channel,
      'version': version,
    }, NetWorkManager.methodGET, DataCallBack(
        businessCallBack: (data) {
          data.forEach((item) {
            ActionItem actionItem = ActionItem.fromJson(item);
            List<ActionItem> actionItems = actionMp[actionItem.actionType] ?? [];
            actionItems.add(actionItem);
            actionMp[actionItem.actionType!] = actionItems;
          });

          print('actionMp:: ${actionMp}');
          generateGridView(actionMp);

        }
    ));
  }


  void generateGridView(Map<String,List<ActionItem>> actionMp) {
    List<ActionItem> danceActions = actionMp['舞蹈']?? [];
    List<ActionItem> behaviorActions = actionMp['动作']?? [];
    List<ActionItem> unexpectedActions = actionMp['搞怪']?? [];

    List<Widget> danceActionsPages = generatePageViewItem(danceActions);
    List<Widget> behaviorActionsPages = generatePageViewItem(behaviorActions);
    List<Widget> unexpectedActionsPages = generatePageViewItem(unexpectedActions);

    setState(() {
      items.clear();
      danceActionsPages.forEach((item) {
        items.add(item);

      });

      behaviorActionsPages.forEach((item) {
        items.add(item);

      });

      unexpectedActionsPages.forEach((item) {
        items.add(item);

      });

      virtualCount = items.length * 100;
      _controller = PageController(initialPage: 0);

      _controller!.addListener(() {
        // 当页面滚动时更新currentIndex
        var value = _controller!.page ?? 0;
        setState(() {
          //todo 研究一下
          currentIndex = value.floor() - 5;
          // 处理可能出现的小数情况
          if ((value - currentIndex).abs() > 0.5) {
            if (value < currentIndex) {
              currentIndex--;
            } else {
              currentIndex++;
            }
          }
          // 将索引限制在[0, N-1]
          currentIndex = (currentIndex % items.length) as int;

          if (currentIndex >= 0 && currentIndex <= danceActionsPages.length -1) {
             //在跳舞的范围内.
             danceChecked = true;
             actionChecked = false;
             unexpectedChecked = false;
          } else if (currentIndex > danceActionsPages.length -1 && currentIndex <= (danceActionsPages.length + behaviorActionsPages.length-1)) {
            danceChecked = false;
            actionChecked = true;
            unexpectedChecked = false;
          } else {
            danceChecked = false;
            actionChecked = false;
            unexpectedChecked = true;
          }

        });
      });


    });

  }


  // 8 个 icon一页.
  List<Widget> generatePageViewItem(List<ActionItem> datas) {

    List<Widget> pages = [];

    List<ActionItem> onePage = [];
    for (int i = 0; i < datas.length; i++) {
      onePage.add(datas[i]);

      if (onePage.length == 8) {
        pages.add(generateOnePage(onePage));
        onePage.clear();
      } else {
        if (i == datas.length -1) {
          pages.add(generateOnePage(onePage));
          onePage.clear();
        }

      }
    }
    return pages;
  }

  Widget generateOnePage(List<ActionItem> onePage) {

    List<Widget> firstLine = [];
    List<Widget> secondLine = [];
    for (int i = 0; i < onePage.length; i++) {
         ActionItem actionItem =  onePage[i];
         if (firstLine.length < 4) {
           firstLine.add(
               renderOneItem(actionItem,i)
           );
         } else {
           secondLine.add(
               renderOneItem(actionItem,i)
           );
         }

    }


    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: firstLine,
        ),
        SizedBox(height: 40.h,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: secondLine,
        ),
      ],
    );
  }

  Widget renderOneItem (ActionItem actionItem,int index) {
   return  GestureDetector(
      onTap: () {
        print('click me : ${actionItem.actionName!}');

      },
      child: Container(
        child: Column(
          children: [
            CachedNetworkImage(
              imageUrl: actionItem.actionIcon!,
              placeholder: (context, url) => CircularProgressIndicator(),
              errorWidget: (context, url, error) => Image.asset('assets/images/ic_dance_list_default.webp',width: 120.w,height: 120.h),
              width: 120.w,
              height: 120.h,
            ),
            SizedBox(height: 11.h,),
            Text(actionItem.actionName!,style: TextStyle(fontSize: 26.sp,color: AppColors.Sub_Title_Color),)
          ],
        ),
      ),
    );
  }

}
